#!/usr/bin/env python
# -*- coding:utf-8 -*-
from OpenSSL import crypto
from OpenSSL._util import lib as cryptolib
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA,SHA256
import base64
def sign(data,private_key):
    rsa_key = RSA.importKey(private_key)
    signer = PKCS1_v1_5.new(rsa_key)
    digest = SHA256.new()
    digest.update(data.encode("utf8"))
    sign = signer.sign(digest)
    signature = base64.b64encode(sign)
    return str(signature,encoding="utf-8")

def pem_publickey(pkey):
    bio = crypto._new_mem_buf()
    cryptolib.PEM_write_bio_PUBKEY(bio, pkey._pkey)
    return crypto._bio_to_string(bio)

def execute(args): 
    private_key_b = "-----BEGIN PRIVATE KEY-----"
    private_key_e = "-----END PRIVATE KEY-----"
    private_key_c = input("请输入私钥: ")
    private_key = private_key_b  +"\n" + private_key_c.strip() +"\n" +private_key_e
    key = crypto.load_privatekey(crypto.FILETYPE_PEM,private_key)
    pubs_key = pem_publickey(key)
    pubs_key = str(pubs_key,encoding="UTF-8")
    public_key = RSA.importKey(pubs_key)
    modulus = hex(public_key.n)[2:].upper()
    exponent = public_key.e
    signModulus = sign(modulus,private_key)
    print("模数: " + modulus)
    print("模数加密: " + signModulus)    
        